package labs.laba_03;

import java.util.ArrayList;

public final class FiguresEngine {
	public final static int DEFAULT_PERCENT = 10; //default percent of width size
	public final static float MIN_WIDTH = 80;
	public final static float MIN_HEIGHT = 80;
	//static FCanvas root;

//	public static void resetCanvas(){
//		root = null;
//		System.gc();
//		root = new FCanvas(0, 0, null, FigureTypes.Canvas);
//	}
//	public static FCanvas getCanvas() {
//		return root;
//	}
	public static Figure getNewFigure(float x, float y, Figure root, FigureTypes type){
		switch (type) {
			case Circle:
				return new FCircle(x, y, root, type);
				//break;
			case Rectangle:
				return new FRectangle(x, y, root, type);
			case Triangle:
				return new FTriangle(x, y, root, type);
			case Canvas:
				break;
			default:
				break;
		}
		return null;
	}
	public static boolean intersection(Figure f1, Figure f2){
		boolean res = false;
		switch(f1.getType()){
			case Circle:
				switch(f2.getType()){
					case Circle:
						res = crossCircleAndCircle((FCircle)f1, (FCircle)f2);
						break;
					default:
						res = crossCircleAndFigure((FCircle)f1, f2);
						break;
				}
				break;
			default:
				switch(f2.getType()){
					case Circle:
						res = crossCircleAndFigure((FCircle)f2, f1);
						break;
					default:
						res = crossFigureAndFigure(f1, f2);
						break;
				}
				break;
		}
		return res;
	}
	private static boolean crossCircleAndCircle(FCircle c1, FCircle c2){
		return (c1.getCenter().getDistanceTo(c2.getCenter()) <= c1.getRadius()+c2.getRadius());
	}
	private static boolean crossCircleAndFigure(FCircle c, Figure f){
		PrimitiveCircle pc = c.getPrimitive();
		ArrayList<PrimitiveLine> pl_list = (ArrayList<PrimitiveLine>)f.getPrimitive();
		for(PrimitiveLine pl : pl_list){
			if(lineCrossCircle(pl, pc)) return true;
		}
		return false;
	}
	private static boolean crossFigureAndFigure(Figure f1, Figure f2){
		ArrayList<PrimitiveLine> pl_list1 = (ArrayList<PrimitiveLine>)f1.getPrimitive();
		ArrayList<PrimitiveLine> pl_list2 = (ArrayList<PrimitiveLine>)f2.getPrimitive();
		for(PrimitiveLine pl1 : pl_list1){
			for(PrimitiveLine pl2 : pl_list2){
				if(lineCrossLine(pl1, pl2)) return true;
			}
		}
		return false;
	}
	private static boolean lineCrossCircle(PrimitiveLine l, PrimitiveCircle c){
		if(c.onwDot(l.getD1()) || c.onwDot(l.getD2())) return true;
		if(l.getDistanceTo(c.getCenter()) <= c.getRadius())
			return true;
		return false;
	}
	private static boolean lineCrossLine(PrimitiveLine l1, PrimitiveLine l2){
		return l1.intersectLine(l2);
	}
}
